<template>
    <div class="on-sale-good-car">
        <div class="search-content">
            <el-form inline>
                <el-form-item label="商品：">
                    <el-input class="search-content-input" v-model="searchContent.goodsName" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="店铺：">
                    <el-input class="search-content-input" v-model="searchContent.storeName" placeholder="请输入所属店铺"></el-input>
                </el-form-item>
                <el-form-item label="车型：">
                    <el-input class="search-content-input" v-model="searchContent.brandCar" placeholder="请输入品牌车型"></el-input>
                </el-form-item>
                <el-form-item label="状态：">
                    <el-select v-model="searchContent.status" placeholder="状态">
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上架时间：">
                    <el-date-picker
                        v-model="searchContent.putawayTime"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
            	<el-form-item label="归属集团：" prop="first_depart_id">
            	    <el-select 
            	        v-model="searchContent.first_depart_id" 
            	        placeholder="请选择集团">
            	        <el-option
            	            v-for="item in groupList"
            	            :key="item.value"
            	            :label="item.label"
            	            :value="item.value">
            	        </el-option>
            	    </el-select>
            	</el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button type="primary" @click="resetSearchData">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="search-list">
            <el-table :data="goodsList" border :height="oHeight">
                <el-table-column
                    align="center"
                    label="首页图片"
                    min-width="100">
                    <template slot-scope="scope">
                        <img style="width: 100px; height: 43.7px;" :src="scope.row.headerImage" alt="">
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    prop="goodsName"
                    label="商品名称"
                    min-width="120">
                </el-table-column>
                <el-table-column
                    align="center"
                    prop="storeName"
                    label="所属店铺"
                    min-width="120">
                </el-table-column>
                <el-table-column
                    align="center"
                    prop="depart_name"
                    label="所属集团"
                    min-width="110">
				</el-table-column>
                <el-table-column
                    align="center"
                    prop="carBrandName"
                    label="品牌车型"
                    min-width="120">
                </el-table-column>
                <el-table-column
                    align="center"
                    label="上架时间"
                    min-width="120">
                    <template slot-scope="scope">
                        <span>{{scope.row.putawayTime | dateFormatter('YYYY-MM-DD HH:mm:ss')}}</span>
                        <br>
                        至
                        <br>
                        <span>{{scope.row.endTime | dateFormatter('YYYY-MM-DD HH:mm:ss')}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    prop="checkStatus"
                    label="审核状态"
                    min-width="90">
                    <template slot-scope="scope">
                        <span :class="scope.row.checkStatus == 3 ? 'check-ing' : (scope.row.checkStatus == 1 ? 'check-pass': 'check-not-pass')">{{scope.row.checkStatus == 3 ? '审核中' : (scope.row.checkStatus == 1 ? '通过': '未通过')}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="审核是否通过"
                    min-width="120">
                    <template slot-scope="scope">
                        <div v-if="scope.row.checkStatus == 3">
                            <span @click="setCheckStatus(scope.row, 1)" style="cursor: pointer" class="yes"></span>
                            <span @click="setCheckStatus(scope.row, 2)" style="cursor: pointer" class="no"></span>
                        </div>
                        <div v-else-if="scope.row.checkStatus == 1">
                            <span class="yes-highlight"></span>
                            <span @click="setCheckStatus(scope.row, 2)" style="cursor: pointer" class="no"></span>
                        </div>
                        <div v-else>
                            <span @click="setCheckStatus(scope.row, 1)" style="cursor: pointer" class="yes"></span>
                            <span class="no-highlight"></span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="置顶"
                    min-width="60">
                    <template slot-scope="scope">
                        <div v-if="scope.row.up" class="yes-highlight" @click="setDown(scope.row)"></div>
                        <div v-else class="yes" @click="setUp(scope.row)"></div>
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="操作"
                    min-width="200">
                    <template slot-scope="scope">
                        <el-button class="copy" @click="handleClipboard(scope.row.id, scope.row.car_type_id)" type="primary">复制链接</el-button>
                        <el-button v-if="scope.row.status == 1" @click="showUnshelveDialog(scope.row)" type="warning">下架</el-button>
                        <el-button @click="lookOverGoodsDetail(scope.row.id)" type="primary">查看详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="bottom">
                <!--<div class="btn-group">
                    <button type="button" class="btn-bottom" @click="unShelveMultiGoods">下架</button>
                    <button type="button" class="btn-bottom" @click="showDeleteDialog">删除</button>
                </div>-->
                <!--分页部分-->
                <div class="btn-group">
                    <el-button type="primary" @click="handleOpen(exportLink)">导出</el-button>
                </div>
                <div class="paginationOne">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="searchContent.currentPage"
                            :page-sizes="[10, 20, 50, 100]"
                            :page-size="searchContent.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>
        <el-dialog
                :before-close="handleClose"
                title="提示"
                :visible="dialogVisible"
                width="30%">
            <span>{{dialogMsg}}</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelUnshelve">取 消</el-button>
                <el-button type="primary" @click="confirmUnshelve">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
	import { resize } from "@/common/js/height.js";
    import Qs from 'qs'
	import {dateFormatter} from "../../../../common/js/util";
    import Clipboard from "clipboard";
	export default {
		data() {
			return {
				options: [
                    {label: '审核中', value: 3},
                    {label: '通过', value: 1},
                    {label: '未通过', value: 2}
                ],
				oHeight: 800,
                searchContent: {
                	goodsName: '',
	                storeName: '',
	                brandCar: '',
	                status: '',
                    first_depart_id: '',
	                putawayTime: '',
	                currentPage: 1,
	                pageSize: +localStorage.getItem('pageSize') || 10
                },
                goodsList: [],
                groupList: [],
				total: 0,
				needUnshelveGoods: null,
				dialogVisible: false,
				dialogMsg: ''
            }
        },
		computed: {
			exportLink() {
				const data = {};
				data.export = 'yes';
				data.goods_name = this.searchContent.goodsName;
				data.store_name = this.searchContent.storeName;
				data.car_brand_name = this.searchContent.brandCar;
				data.audit_status = this.searchContent.status;
				data.first_depart_id = this.searchContent.first_depart_id;
		        if (this.searchContent.putawayTime) {
		        	const putawayMS = this.searchContent.putawayTime[0].getTime();
		        	const endMS = this.searchContent.putawayTime[1].getTime();
		        	if (putawayMS == endMS) {
				        data.putaway_time = dateFormatter('YYYY-MM-DD HH:mm:ss', putawayMS);
				        data.end_time = dateFormatter('YYYY-MM-DD HH:mm:ss', endMS + (24 * 60 * 60 - 1) * 1000);
                    } else {
				        data.putaway_time = dateFormatter('YYYY-MM-DD HH:mm:ss', putawayMS);
				        data.end_time = dateFormatter('YYYY-MM-DD HH:mm:ss', endMS + (24 * 60 * 60 - 1) * 1000);
                    }
                }
				let domain = document.domain;
				if (domain != 'admin.mycjj.com' && domain != 'admin.chejj.cn') {
					domain = 'admin.chejj.cn'
				}
				return location.protocol + '//' + domain.replace('admin', 'api') + '/admin/preferential_car/index.php?act=preferentialCar&op=preferentialCarExport&' + Qs.stringify(data);
			}
		},
        methods: {
        	handleGroup() {
        	    this.$http.post('/crm/coupons/index.php?act=statistics&op=getCouponDepart')
        	    .then(res => {
        	        if (res.data) {
        	            this.groupList = [
        	                { label: '全部', value: 0 },
        	                ...res.data.map(item => ({ 
        	                    label: item.depart_name, 
        	                    value: parseInt(item.depart_id) 
        	                }))
        	            ]
        	        }
        	    }).catch(error => {
        	        error && this.$message.error(`${error}`)
        	    })
        	},
            handleClipboard(id, typeId) {//复制事件
                const clipboard = new Clipboard(".copy", {
                    text: () => `/pages/PreferentialCarDetail/PreferentialCarDetail?id=${id}&type_id=${typeId}`
                });
                clipboard.on("success", e => {
                    this.$message.success("复制成功");
                    e.clearSelection() // 清除文字选中状态
                    clipboard.destroy() // 释放内存
                })
                clipboard.on("error", e => {
                    this.$message.warning("该浏览器不支持自动复制") // 不支持复制
                    clipboard.destroy() // 释放内存
                })
            },
            handleOpen(url) {
                window.open(url)
            },
	        resetSearchData() {
		        this.searchContent.goodsName = '';
		        this.searchContent.storeName = '';
		        this.searchContent.brandCar = '';
		        this.searchContent.status = '';
		        this.searchContent.putawayTime = '';
				this.searchContent.first_depart_id = '';
				this.getListData();
	        },
	        search() {
		        this.searchContent.currentPage = 1;
		        this.getListData();
	        },
	        handleSizeChange(pageSize) {
		        this.searchContent.pageSize = pageSize;
				localStorage.setItem('pageSize', pageSize);
		        this.searchContent.currentPage = 1;
		        this.getListData();
            },
	        handleCurrentChange(page) {
		        this.searchContent.currentPage = page;
		        this.getListData();
            },
	        getListData() {
		        var data = {};
		        data.page = this.searchContent.currentPage;
		        data.eachNum = this.searchContent.pageSize;
		        data.goods_name = this.searchContent.goodsName;
		        data.store_name = this.searchContent.storeName;
		        data.car_brand_name = this.searchContent.brandCar;
                data.first_depart_id = this.searchContent.first_depart_id;
		        if (this.searchContent.putawayTime) {
		        	const putawayMS = this.searchContent.putawayTime[0].getTime();
		        	const endMS = this.searchContent.putawayTime[1].getTime();
		        	if (putawayMS == endMS) {
				        data.putaway_time = dateFormatter('YYYY-MM-DD HH:mm:ss', putawayMS);
				        data.end_time = dateFormatter('YYYY-MM-DD HH:mm:ss', endMS + (24 * 60 * 60 - 1) * 1000);
                    } else {
				        data.putaway_time = dateFormatter('YYYY-MM-DD HH:mm:ss', putawayMS);
				        data.end_time = dateFormatter('YYYY-MM-DD HH:mm:ss', endMS + (24 * 60 * 60 - 1) * 1000);
                    }
                }
		        data.audit_status = this.searchContent.status;
		        var that = this;
		        this.$http.post('/admin/preferential_car/index.php?act=preferentialCar&op=auditList', data).then(function(res) {
			        if (res.code == 1) {
				        if (res.data && res.data.list.length) {
					        that.goodsList = res.data.list.map(function(item) {
						        return {
							        id: item.id,
							        car_type_id: item.car_type_id,
							        goodsName: item.goods_name,
							        headerImage: item.header_image,
                                    storeName: item.store_name,
							        carBrandName: item.car_brand_name,
							        putawayTime: item.putaway_time * 1000,
							        endTime: item.end_time * 1000,
							        checkStatus: item.audit_status,
							        putawayPrice: item.special_price * 1000,
							        stock: item.inventory,
                                    status: item.status,
                                    depart_name: item.depart_name
						        }
					        });
					        that.total = parseInt(res.data.totalNum);
				        } else {
					        that.goodsList = [];
					        that.total = 0;
				        }
			        }
			        else if (res.code == 2001) {
				        that.goodsList = [];
				        that.total = 0;
			        }
			        else {
				        alert(res.msg);
			        }
		        })
	        },
            async setCheckStatus(goodsItem, checkStatus) {
                try {
                    let reject_reason = '', cancel = false
                    if (checkStatus === 2) {
                        reject_reason = await this.$prompt('请输入不通过原因', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            inputPlaceholder: '填写不通过原因',
                            inputValidator: value => {
                                if (!value) return '原因不能为空'
                                else if(value.length > 100) return '长度不能超过100个字符'
                                else return true
                            }
                        }).then(({ value }) => value).catch(() => (cancel = true))
                    }
                    if (cancel) return
				    const res = await this.$http.post('/admin/preferential_car/index.php?act=preferentialCar&op=auditGoods', {
				    	id: goodsItem.id,
				    	audit_status: checkStatus,
                        reject_reason
				    })
                    if (res.code == 1) {
		                goodsItem.checkStatus = checkStatus
				    } else {
                        throw res.msg
				    }
                } catch(error) {
                    this.$message.error(`${error}`)
                }
            },
	        setUp(goodsItem) {
	        	const goodsIndex = this.goodsList.findIndex(item => item.id == goodsItem.id)
		        this.goodsList.splice(goodsIndex, 1)
		        goodsItem.up = 1
		        this.goodsList.unshift(goodsItem)
            },
	        setDown(goodsItem) {
		        const goodsIndex = this.goodsList.findIndex(item => item.id == goodsItem.id)
		        this.goodsList.splice(goodsIndex, 1)
		        goodsItem.up = 0
		        this.goodsList.push(goodsItem)
	        },
	        unshelveGoods(goodsItem) {
		        this.$http.post('/admin/preferential_car/index.php?act=preferentialCar&op=pullOffShelves', {
			        id: goodsItem.id
		        }).then(res => {
			        if (res.code == 1) {
				        goodsItem.status = 2
			        } else {
				        alert(res.msg)
			        }
		        })
            },
	        showUnshelveDialog(goodsItem) {
		        this.needUnshelveGoods = goodsItem
		        this.dialogMsg = '此商品还未到下架时间，确认下架？';
		        this.dialogVisible = true;
	        },
	        handleClose() {
		        this.cancelUnshelve();
	        },
	        cancelUnshelve() {
		        this.dialogVisible = false;
		        this.dialogMsg = '';
		        this.needUnshelveGoods = null;
	        },
	        confirmUnshelve() {
		        this.unshelveGoods(this.needUnshelveGoods);
		        this.cancelUnshelve();
	        },
	        lookOverGoodsDetail(id) {
	        	this.$router.push(`/home/operate-panel/goods-management/goods-detail?id=${id}`)
            }
        },
        mounted() {
	        resize(this)
        },
		created() {
			this.$parent.tabLists = [
				{"label": "特惠好车", "name": 'on-sale-good-car'},
				{"label": "报名信息", "name": 'reg-info'}
			]
			this.getListData();
            this.handleGroup();
		},
		name: "on-sale-good-car"
	}
</script>

<style lang="scss" scoped>
    .on-sale-good-car {
        .search-content {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            &-input {
                width: 200px;
            }
            .putaway-time-wrapper {
                .putaway-time-label {
                    font-size: 14px;
                }
                display: flex;
                align-items: center;
                /deep/.el-range-separator {
                    box-sizing: content-box;
                }
            }
        }
    }
    .yes {
        display: inline-block;
        width: 20px;
        height: 20px;
        cursor: pointer;
        background-image: url("./img/yes.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100% 100%;
    }
    .yes-highlight {
        display: inline-block;
        width: 20px;
        height: 20px;
        cursor: pointer;
        background-image: url("./img/yes-highlight.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100% 100%;
    }
    .no {
        display: inline-block;
        width: 20px;
        height: 20px;
        cursor: pointer;
        background-image: url("./img/no.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100% 100%;
        margin-left: 15px;
    }
    .no-highlight {
        display: inline-block;
        width: 20px;
        height: 20px;
        cursor: pointer;
        background-image: url("./img/no-highlight.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100% 100%;
        margin-left: 15px;
    }
    .check-ing {
        color: #FC303D;
    }
    .check-pass {
        color: #189AF9;
    }
    .check-not-pass {
        color: #9D9D9D;
    }
	.bottom{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>